import { Prefab, instantiate, resources, Node, find } from 'cc'
import Singleton from '../Base/Singleton'
export default class PrefabManager extends Singleton {
    private _prefabMap: Map<string, Node> = new Map()
    private _prefabBaseUrl: string = 'prefabs'
    //弹窗容器
    dialogBox: Node
    static get Instance() {
        return super.getInstance<PrefabManager>()
    }
    showDialog(name: string) {
        if (!this.dialogBox) {
            const dialogBox = find('Canvas/DialogBox')
            this.dialogBox = dialogBox
        }
        return new Promise<Node>((resolve, reject) => {
            if (this._prefabMap.has(name)) {
                const node = this._prefabMap.get(name)
                node.active = true
                resolve(node)
            } else {
                this.loadPrefab(name).then(node => resolve(node))
            }
        })
    }
    /**
     * 加载prefab并注册到_prefabMap中
     * @param name 预制体名称
     */
    loadPrefab(name: string) {
        return new Promise<Node>((resolve, reject) => {
            const path = `${this._prefabBaseUrl}/${name}`
            resources.load(path, Prefab, (err, prefab) => {
                if (err) {
                    // TODO 弹出一个错误提示预制体
                    reject(err)
                    throw new Error(`加载资源【${name}】失败`)
                }
                const node = instantiate(prefab)
                node.setParent(this.dialogBox)
                this.add(name, node)
                resolve(node)
            })
        })
    }
    hideDialog(name: string) {
        const node = this._prefabMap.get(name)
        node.active = false
    }
    hideDialogs(path: string[]) {
        if (!path || !Array.isArray(path)) {
            return
        }
        path.forEach((dialogName: string) => {
            if (this._prefabMap.has(dialogName)) {
                const dialog = this._prefabMap.get(dialogName)
                dialog.active = false
            }
        })
    }
    // 注册
    add(path: string, prefab: Node) {
        if (this._prefabMap.has(path)) {
            return
        }
        this._prefabMap.set(path, prefab)
    }
    // 移除
    remove(path: string) {
        if (!this._prefabMap.has(path)) {
            return
        }
        this._prefabMap.delete(path)
    }
    // 获取对应节点
    get(path: string): Node {
        return this._prefabMap.get(path)
    }
    active(path) {}
}
